package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("sendMsg")
    //为什么不能用Long phone 接收
    // TODO: 2022/2/28 0028  
    public R<String> send(HttpServletRequest request, @RequestBody User user) {


        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode4String(4);

        //模拟发短信推送验证码
        log.info("code={}", code);

        //把验证码存到session里,在登录时与用户输入进行比对
      //  request.getSession().setAttribute("code", code);

        //存到redis里,由于redis全用户公用，所以key值不能重复
        redisTemplate.opsForValue().set("code_"+phone,code,2, TimeUnit.MINUTES);

        return R.success("短信发送成功");

    }

    @PostMapping("login")
    public R<User> login(HttpServletRequest request, @RequestBody Map<String, String> map) {

        //获取手机号和验证码
        String code = map.get("code");
        String phone = map.get("phone");
        System.out.println(code + " " + phone);


        //比较验证码输入是否正确
      //  String sessionCode = (String) request.getSession().getAttribute("code");

        //从redis里取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("code_" + phone);


        if (!code.equals(redisCode)) {
            return R.error("验证码不正确");
        }


        //判断用户是否是新用户
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);

        if (user==null) {
            user.setPhone(phone);
            userService.save(user);
        }
        //在session里保存登录状态
        request.getSession().setAttribute("user", user.getId());

        //登录成功即删除验证码
        redisTemplate.delete("code_"+phone);
        return R.success(user);

    }


}
